# -*- coding: utf-8 -*-
# @Time    : 2018/7/1 15:14
# @Author  : Feng Cheng
# @Email   : fengcheng@pku.edu.cn


import os
import sys
import pdb

sys.path.append(os.path.dirname(__name__))
sys.path.append(os.path.join(os.path.dirname(__name__), '..'))

from collections import Counter
from collections import defaultdict
import pandas as pd
import string
import datetime
import matplotlib.pyplot as plt


class Denoise():
    def __init__(self, addr='originHolding.csv'):
        import pandas as pd
        holdings = pd.read_csv(addr)
        holdings['datetime']=holdings['datetime'].apply(lambda x:datetime.datetime.strptime(x,'%Y-%m-%d'))
        # import pdb
        # pdb.set_trace()
        newFrame = pd.DataFrame(columns=holdings['instrument'].unique(), index=holdings['datetime'].unique())
        newFrame = newFrame.fillna(0)

        for i in range(holdings.index.shape[0]):
            newFrame.loc[holdings['datetime'][i], holdings['instrument'][i]] = holdings['score'][i]
        self.data = newFrame
        self.data = self.data.iloc[50:,]
#         self.data.index=self.data.index.apply(lambda x:datetime.datetime.strptime(x,'%Y-%m-%d'))
#         self.data.plot()
#         plt.show()

    def toMultiIndex(self, data):
        u = {}
        for x in data.columns:
            u[x] = data[[x]][:]
            u[x].loc[:, 'instrument'] = x
            u[x].columns = ['score', 'instrument']
        return pd.concat(u, axis=0).fillna(0)

    def denoise_ma(self, cycle=3):
        roll = self.data.rolling(window=cycle, min_periods=1)
        data_denoised = roll.mean()
#         data_denoised.plot()
#         plt.show()

        return  data_denoised ,self.toMultiIndex(data_denoised)[['score']]

    def denoise_ewm(self, cycle=50):
        # roll = self.data.rolling(window=cycle, min_periods=cycle)
        data_denoised = self.data.ewm(halflife=cycle).mean(cycle=cycle)
#         data_denoised.plot()
#         plt.show()
        return  data_denoised ,self.toMultiIndex(data_denoised)[['score']]

    def metric(self):
        pass
if __name__=='__main__':

    d = Denoise()
    ma, position = d.denoise_ma()
    print(ma)
